
#import "ImageDownloader.h"
#import "ASIHttpRequest.h"


@implementation ImageDownloader

@synthesize _Connection;
@synthesize _sURL;

-(id)init
{
	self = [super init];
	if(self)
	{
		_oResult = [[NSMutableData alloc] initWithCapacity:128];
		_bCanceled = NO;
	}
	return self;
}

-(void)dealloc
{
	if(_ImageDownloaderDelegate)
		[_ImageDownloaderDelegate release];
	self._sURL = nil;
	self._Connection = nil;
	[_oResult  release];
	[super dealloc];
}


- (void)getImageFromURL:(NSString*)imageURL delegate:(id <ImageDownloaderDelegate>)dlgt
{
	[self retain];
	_ImageDownloaderDelegate = [dlgt retain];
	self._sURL = imageURL;

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]];
    
    _Connection = [[NSURLConnection alloc] initWithRequest:req 
                                                  delegate:self 
                                          startImmediately:YES];
    if (!_Connection) 
    {
        [_ImageDownloaderDelegate receivedImage:nil sender:self];
        [self release];
    }
//	[ increaseNetworkActivityIndicator];
	
}

#pragma mark NSURLConnection delegate methods


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_oResult setLength:0];
}


- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_oResult appendData:data];
}


- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//	[ decreaseNetworkActivityIndicator];
	[_ImageDownloaderDelegate receivedImage:nil sender:self];
    [self release];
}


- (NSCachedURLResponse *) connection:(NSURLConnection *)connection 
                   willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
     return cachedResponse;
}



- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//	[ decreaseNetworkActivityIndicator];
	[_ImageDownloaderDelegate receivedImage:[UIImage imageWithData:_oResult] sender:self];
	[self release];

}

- (void)cancel
{
	_bCanceled = YES;
	if(_Connection)
	{
		[_Connection cancel];
//		[ decreaseNetworkActivityIndicator];
		[self release];
	}
	[_ImageDownloaderDelegate receivedImage:nil sender:self]; 
}

- (BOOL)canceled
{
	return _bCanceled;
}


@end
